04 / 11

You have a class that validates user input. The validation rules change frequently. Which pattern would you use and why?

Difficulty: 4/10

Strategy Pattern for Evolving Validation Rules

When validation rules change frequently, I would avoid a large validator containing nested if/else or switch statements. I would use the Strategy Pattern, where each validation policy is encapsulated behind an interface. The appropriate strategy can then be selected based on product, customer type, version, jurisdiction, or configuration.

javascript
  1. 1

    Each rule has one responsibility.

  2. 2

    New rules can be added without changing the validator.

  3. 3

    Rules can be independently unit tested.

  4. 4

    Rules can be composed dynamically.

  5. 5

    For highly configurable validation, a rules engine or specification pattern may be appropriate.

Follow-up Questions

  • When would you use Specification Pattern instead?
  • How would rules be configured dynamically?
  • How would you handle validation error messages?
Share

Share via WhatsApp, X, Facebook, LinkedIn or copy link. Open Graph preview enabled.